package com.heima.comment.service.impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.service.CommentHotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查找热点评论
     *
     * @param entryId
     * @param apComment
     */
    @Override
    @Async //****异步执行
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        //1.查询当前文章所有热点文章，并按点赞数倒叙排序
        List<ApComment> apCommentHotList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(entryId)
                        .and("type").is(0)  //文章
                        .and("flag").is(1))//热点
                        .with(Sort.by(Sort.Direction.DESC, "likes"))
                        .limit(5)//限制5条
                , ApComment.class);//点赞数倒叙

        //2.当前是否有热点评论，无则直接新增
        if (apCommentHotList == null || apCommentHotList.size() < 5) {
            apComment.setFlag(1);
            apComment.setUpdatedTime(new Date());
            mongoTemplate.save(apComment);
            log.info("***新增热点文章成功");
        }
        //3.判断当前评论点赞数是否大于热点评论中的最小热点评论
        if (apCommentHotList != null || apCommentHotList.size() > 0) {
            ApComment lastApCommentHost = apCommentHotList.get(apCommentHotList.size() - 1);//最后一条热点评论
            if (apComment.getLikes() > lastApCommentHost.getLikes()) {
                if (apCommentHotList.size() < 5) {//当前热点评论数量<5时，直接新增
                    apComment.setFlag(1);
                    apComment.setUpdatedTime(new Date());
                    mongoTemplate.save(apComment);
                    log.info("***新增热点文章成功");
                } else { //当前评论替换热点评论
                    //热点评论变为普通评论
                    lastApCommentHost.setFlag(0);
                    lastApCommentHost.setUpdatedTime(new Date());
                    mongoTemplate.save(lastApCommentHost);
                    //当前评论变为热点评论
                    apComment.setFlag(1);
                    apComment.setUpdatedTime(new Date());
                    mongoTemplate.save(apComment);
                    log.info("***新增热点文章成功");
                }
            }
        }
    }
}
